package com.alibaba.csp.sentinel.dashboard.rule.nacos.rule;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.AuthorityRuleEntity;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRulePublisher;
import com.alibaba.csp.sentinel.dashboard.rule.nacos.NacosConstants;
import com.alibaba.csp.sentinel.dashboard.rule.nacos.NacosPropertiesConfiguration;
import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.util.AssertUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.config.ConfigService;

/**
 * 动态上传授权规则到Nacos配置中心
 */
@Service
public class AuthorityRuleNacosPublisher implements DynamicRulePublisher<List<AuthorityRuleEntity>> {

	private static Logger logger = LoggerFactory.getLogger(AuthorityRuleNacosPublisher.class);

	@Autowired
	private NacosPropertiesConfiguration nacosPropertiesConfiguration;

	@Autowired
	private ConfigService configService;

	@Autowired
	private Converter<List<AuthorityRuleEntity>, String> converter;

	/**
	 * 将规则转换成配置文件格式，然后上传到Nacos配置中心
	 *
	 * @param appName
	 * @param rules   list of rules to push
	 * @throws Exception
	 */
	@Override
	public void publish(String appName, List<AuthorityRuleEntity> rules) throws Exception {
		AssertUtil.notEmpty(appName, "appName cannot be empty");
		logger.info(">>> push FlowRule to Nacos Config:{}", JSON.toJSONString(rules));
		if (rules != null) {
			String dataId = new StringBuffer(appName).append(NacosConstants.AUTHORITY_DATA_ID_SUFFIX).toString();
			configService.publishConfig(dataId, nacosPropertiesConfiguration.getGroupId(), converter.convert(rules));
		}
	}
}
